package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;


public class ClientListener extends Thread {
	private Socket s;
	private BufferedReader in;
	private PrintWriter out;
	private Server ser;
	private String name;
	
	public ClientListener(Socket s, Server ser) throws IOException {
		this.s = s;
		this.ser = ser;
		this.out = new PrintWriter(s.getOutputStream(), true);
		this.in = new BufferedReader(new InputStreamReader(s.getInputStream()));
	}
	
	@Override
	public void run() {
		ArrayList<String> message;
		try {
			message = Parser.parse(in.readLine());
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		
		// serio, != ? zmiast equals
		if (!message.get(0).equals("H") || !ser.addUser(message.get(1), out)) {	//sprawdza, czy dostal "H nick" i czy nick jest wolny
			out.println("UT");	//jak nie, to odmawia polaczenia // .print, serio?
			try {
				s.close();
			} catch (IOException e) {
			}
			return;
		}
		out.println("OK"); 
		name = message.get(1);
		
		while(true) {
			String text;
			try {
				text = in.readLine();
				if (text == null) throw new IOException();
				message = Parser.parse(text);
			} catch (IOException e) {	//polaczenie przerwane - ubijamy wszystko
				ser.removeUser(name);
				try {
					s.close();
				} catch (IOException e1) {
				}
				return;
			}
			if (message.get(0).equals("MA")) {	//generowanie wiadomosci do wszystkich
				System.out.println("Sending to all, message.size() = " + String.valueOf(message.size()));
				if (message.size() == 2) ser.addToSendForAll("MA " + name + " " + message.get(1));
				else if (message.size() == 3) ser.addToSendForAll("MA " + name + " " + message.get(1) + " " + message.get(2));
			}
			if (message.get(0).equals("MP")) {	//generowanie wiadomosci prywatnej
				ser.addToSendForOne("MP " + name + " " + message.get(2), message.get(1));
			}
		}
	}
}